﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace QunProject.Web.App_Start
{
    /// <summary>
    /// 检查用户是否登录
    /// 如果是Ajax操作，则返回错误提示Json数据
    /// 如果是普通post或页面view者直接跳转到登录页
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
    public class CheckLoginAttribute : FilterAttribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            //throw new NotImplementedException();
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    var json = new Common.JsonData();
                    json.ErrorAlert("登录已过期，请重新登录");
                    filterContext.Result = new JsonResult()
                    {
                        Data = json,
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl, true);
                }
            }
        }
    }
}